import { CheckboxGroupField, CommonField } from '@/pages/OrderModule/common/components/CommonForm';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import { Form, Input, Spin } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { TagLabel } from '../TagLabel';
import Style from './index.module.less';
import { queryTagList } from './server';

export const TagField = (props) => {
  const { filterable, fieldKey, setTagList } = props;
  const [tagName, setTagName] = useState('');
  const [commitSearch, setCommitSearch] = useState('');

  const { loading: tagListLoading, data: tagListResp, fetch: fetchTagList } = useFetch(queryTagList, {}, false);
  useEffect(() => {
    fetchTagList().then(res => {
      setTagList?.(res?.data || []);
    })
  }, []);

  const tagList = useMemo(() => {
    if (commitSearch) {
      return tagListResp?.data?.filter((item) => item.name.includes(commitSearch)) || [];
    } else {
      return tagListResp?.data || [];
    }
  }, [tagListResp, commitSearch]);

  return (
    <>
      {filterable && (
        <Form.Item>
          <CommonField
            Component={Input}
            props={{
              placeholder: '回车搜索',
              onChange: (e) => {
                setTagName(e.target.value);
              },
              onKeyDown: (e) => {
                if (e.key === 'Enter') {
                  setCommitSearch(tagName);
                }
              },
            }}
          />
        </Form.Item>
      )}
      <Spin spinning={tagListLoading}>
        <Form.Item name={fieldKey}>
          <CommonField
            Component={CheckboxGroupField}
            props={{
              className: Style.orderTag_checkbox_wrap,
              numCol: 5,
              suffixAction: ['all'],
              title: {
                className: Style.orderTag_title,
                as: 's2',
                symbol: true,
                title: '选择标签',
              },
              options: tagList.map((item, key) => ({
                label: <TagLabel key={item.name} name={item.name}></TagLabel>,
                value: item.id,
              })),
            }}
          />
        </Form.Item>
      </Spin>
    </>
  );
};
export default TagField;
